import keyboard
import sounddevice as sd
print(sd.query_devices())
import sys,os
import time
import zmq
from threading import Thread, current_thread
def target01():
    context = zmq.Context()
    socket = context.socket(zmq.REQ)
    socket.connect("tcp://localhost:5555")
    string_to_send = "is ok?"
    
    while True:
        print(f"sending {string_to_send}")
        socket.send(string_to_send.encode())
        num = socket.poll(1000)
        if num == 0:
            exit_flag = True
            os._exit(0)
        message = socket.recv()
        print(f"reversed: {message}")
        time.sleep(3)
 

# 创建线程
thread01 = Thread(target=target01)
# 启动线程
thread01.start() 


def toggleflag(e):
    global flag
    flag = not flag
    if flag :
        print("Streaming audio (press Ctrl+C to stop)...")
    else:
        print("Stopped streaming audio")
flag = False
in_stream = sd.InputStream(channels=1)
in_stream.start()
# out_stream = sd.OutputStream(channels=1)
out_stream = sd.OutputStream(channels=1,device="CABLE Input (VB-Audio Virtual Cable), Windows WASAPI")
out_stream.start()
keyboard.on_press_key("`", toggleflag)
try:
    while True:
        if flag: 
            (data,info )= in_stream.read(2048)
            # print(data)
            # print(info)
            out_stream.write(data)
        else:
            time.sleep(1)
except KeyboardInterrupt:
    pass
in_stream.stop()
out_stream.stop()

